package com.liangxy.news.ui.main.profile;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;

import com.liangxy.news.R;
import com.liangxy.news.database.AppDatabase;
import com.liangxy.news.model.User;
import com.liangxy.news.util.SharedPreferencesManager;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Fragment for changing user password
 */
public class ChangePasswordFragment extends Fragment {
    
    private static final String TAG = "ChangePasswordFragment";
    private static final String ARG_USER_ID = "user_id";
    
    private String userId;
    private EditText etCurrentPassword;
    private EditText etNewPassword;
    private EditText etConfirmPassword;
    private Button btnChangePassword;
    private Toolbar toolbar;
    
    private SharedPreferencesManager preferencesManager;
    private ExecutorService executorService;
    
    /**
     * Create a new instance of ChangePasswordFragment
     * @param userId User ID
     * @return ChangePasswordFragment instance
     */
    public static ChangePasswordFragment newInstance(String userId) {
        ChangePasswordFragment fragment = new ChangePasswordFragment();
        Bundle args = new Bundle();
        args.putString(ARG_USER_ID, userId);
        fragment.setArguments(args);
        return fragment;
    }
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            userId = getArguments().getString(ARG_USER_ID);
        }
        
        preferencesManager = new SharedPreferencesManager(requireContext());
        executorService = Executors.newSingleThreadExecutor();
    }
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_change_password, container, false);
        
        // 初始化组件
        etCurrentPassword = view.findViewById(R.id.etCurrentPassword);
        etNewPassword = view.findViewById(R.id.etNewPassword);
        etConfirmPassword = view.findViewById(R.id.etConfirmPassword);
        btnChangePassword = view.findViewById(R.id.btnChangePassword);
        toolbar = view.findViewById(R.id.toolbar);
        
        // 设置工具栏
        try {
            if (getActivity() instanceof AppCompatActivity) {
                // 直接设置工具栏
                toolbar.setTitle(R.string.change_password);
                toolbar.setNavigationIcon(R.drawable.ic_back);
                
                // 设置返回按钮点击事件
                toolbar.setNavigationOnClickListener(v -> {
                    if (getActivity() != null && getActivity().getSupportFragmentManager().getBackStackEntryCount() > 0) {
                        getActivity().getSupportFragmentManager().popBackStack();
                    }
                });
            }
        } catch (Exception e) {
            Log.e(TAG, "设置工具栏时出错: " + e.getMessage(), e);
        }
        
        // 设置修改密码按钮点击事件
        btnChangePassword.setOnClickListener(v -> changePassword());
        
        return view;
    }
    
    /**
     * 修改密码
     */
    private void changePassword() {
        String currentPassword = etCurrentPassword.getText().toString().trim();
        String newPassword = etNewPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();
        
        // 验证输入
        if (currentPassword.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()) {
            Toast.makeText(requireContext(), "请填写所有字段", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (!newPassword.equals(confirmPassword)) {
            Toast.makeText(requireContext(), "两次输入的新密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (newPassword.length() < 6) {
            Toast.makeText(requireContext(), "新密码长度不能少于6位", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 验证当前密码并更新
        verifyAndUpdatePassword(currentPassword, newPassword);
    }
    
    /**
     * 验证当前密码并更新密码
     * @param currentPassword 当前密码
     * @param newPassword 新密码
     */
    private void verifyAndUpdatePassword(String currentPassword, String newPassword) {
        executorService.execute(() -> {
            try {
                // 获取数据库实例
                AppDatabase database = AppDatabase.getInstance(requireContext().getApplicationContext());
                
                // 获取当前用户
                User user = database.userDao().getUserByIdSync(userId);
                
                if (user != null) {
                    // 验证当前密码
                    if (user.getPassword().equals(currentPassword)) {
                        // 更新密码
                        user.setPassword(newPassword);
                        database.userDao().update(user);
                        
                        // 更新SharedPreferences中的用户信息
                        preferencesManager.saveUser(user);
                        
                        // 显示成功消息
                        if (isAdded() && getActivity() != null) {
                            requireActivity().runOnUiThread(() -> {
                                if (isAdded()) {
                                    Toast.makeText(requireContext(), "密码修改成功", Toast.LENGTH_SHORT).show();
                                    if (getActivity() != null) {
                                        getActivity().onBackPressed();
                                    }
                                }
                            });
                        }
                    } else {
                        // 当前密码错误
                        showToastOnMainThread("当前密码错误");
                    }
                } else {
                    // 用户不存在
                    showToastOnMainThread("用户信息不存在");
                }
            } catch (Exception e) {
                Log.e(TAG, "修改密码出错: " + e.getMessage(), e);
                showToastOnMainThread("修改密码失败: " + e.getMessage());
            }
        });
    }
    
    /**
     * 在主线程上显示Toast消息
     * @param message 要显示的消息
     */
    private void showToastOnMainThread(final String message) {
        if (isAdded() && getActivity() != null) {
            requireActivity().runOnUiThread(() -> {
                if (isAdded()) {
                    Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (executorService != null) {
            executorService.shutdown();
        }
    }
} 